import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injector } from '@angular/core';
import { FormBasicService, DomService, DesignerEnvType, FormDeclaration, Subscription } from '@farris/designer-services';
import { Subject } from 'rxjs';

/**
 * 对表单DOM节点进行适配检查
 */
export class AdaptOldFormService {
    private formBasicServ: FormBasicService;

    private domServ: DomService;

    private http: HttpClient;

    constructor(private injector: Injector) {

        this.formBasicServ = this.injector.get(FormBasicService);
        this.domServ = this.injector.get(DomService);
        this.http = this.injector.get(HttpClient);
    }

    /**
     * 对DOM节点进行兼容性适配检查
     */
    adaptOldForm() {
        // 设计器自动补充的属性，不记录变更
        window.suspendChangesOnForm = true;

        this.adaptOldMoudle();
        // this.adaptOldSchema();
        this.adaptFormOptions();

        // 适配表达式
        if (!this.domServ.module.hasOwnProperty.call('expressions')) {
            this.domServ.module.expressions = [];
        }

        window.suspendChangesOnForm = false;
    }

    /**
     * Module层的属性缺失
     */
    private adaptOldMoudle() {

        // 补充表单创建时的模板id---用于表单升级
        if (!this.domServ.module.templateId && this.domServ.module.bootstrap) {
            this.domServ.module.templateId = this.domServ.module.bootstrap;
        }

        // 设计时：增加表单所在工程名
        if (this.formBasicServ.envType === DesignerEnvType.designer && !this.domServ.module.projectName &&
            this.formBasicServ.formMetaBasicInfo && this.formBasicServ.formMetaBasicInfo.relativePath) {
            const paths = this.formBasicServ.formMetaBasicInfo.relativePath.split('/');
            this.domServ.module.projectName = paths[3];
        }

        // 补充组合表单-组件声明-命令所在componentId的缺失
        if (this.domServ.module.declarations && this.domServ.module.declarations.commands &&
            this.domServ.module.declarations.commands.length) {
            this.domServ.module.declarations.commands.forEach(command => {
                if (command && !command.componentId) {
                    const pathArray = command.path.split('.');
                    if (pathArray.length > 1) {
                        const viewModelId = pathArray[pathArray.length - 2];
                        const cmp = this.domServ.module.components.find(c => c.viewModel === viewModelId);
                        if (cmp) {
                            command.componentId = cmp.id;
                        }
                    }

                }
            });
        }

        // 补充组合表单-组件通讯-参数映射-目标参数所在的路径targetPath
        if (this.domServ.module.subscriptions && this.domServ.module.subscriptions.length) {
            this.domServ.module.subscriptions.forEach(subscription => {
                if (subscription.targetComponent && subscription.paramMappings && subscription.paramMappings.length) {
                    const targetDeclartion = this.getDeclarationForSubscriptionTarget(subscription);
                    if (!targetDeclartion) {
                        return;
                    }
                    subscription.paramMappings.forEach(paramMapping => {
                        if (!paramMapping.targetPath && paramMapping.targetCode && targetDeclartion.states &&
                            targetDeclartion.states.length) {
                            const targetState = targetDeclartion.states.find(state => state.code === paramMapping.targetCode);
                            paramMapping.targetPath = targetState.path;
                        }
                    });
                }
            });
        }

        // 补充页面按钮的配置
        if (!this.domServ.module.toolbar) {
            this.domServ.module.toolbar = {
                items: {},
                configs: {}
            };
        }
        // 补充页面展示形式
        if (!this.domServ.module.showType) {
            this.domServ.module.showType = 'page';
        }

        // 补充组件声明
        if (!this.domServ.module.declarations) {
            this.domServ.module.declarations = {
                events: [],
                commands: [],
                states: []
            };
        }
        // 补充组件通讯
        if (!this.domServ.module.subscriptions) {
            this.domServ.module.subscriptions = [];
        }
        // 补充外部模块
        if (!this.domServ.module.extraImports) {
            this.domServ.module.extraImports = [];
        }

        // 补充表单被组合标识
        // if (!this.domServ.options.hasOwnProperty.call('canBeComposed')) {
        //   const componentTemplate = ['list-component', 'tree-component', 'list-view-component'];
        //   this.domServ.options.canBeComposed = componentTemplate.includes(this.domServ.module.templateId);
        // }

    }

    private getDeclarationForSubscriptionTarget(subscription: Subscription): FormDeclaration {
        let targetComponent;
        // 引入的外部表单
        if (this.domServ.module.externalComponents) {
            targetComponent = this.domServ.module.externalComponents.find(c => c.id === subscription.targetComponent);
            if (targetComponent) {
                return targetComponent.declarations;
            }
        }
        // 当前表单
        if (this.formBasicServ && this.formBasicServ.formMetaBasicInfo &&
            this.formBasicServ.formMetaBasicInfo.code === subscription.targetComponent) {
            return this.domServ.module.declarations;
        }
    }

    /**
     * 旧表单增加eapiId。适用于设计时环境
     */
    // private adaptOldSchema() {
    //     if (this.formBasicServ.envType !== DesignerEnvType.designer) {
    //         return;
    //     }

    //     const schema = this.domServ.module.schemas[0];
    //     if (schema.eapiId && schema.eapiNameSpace) {
    //         return;
    //     }

    //     const subject = new Subject<any>();

    //     // 1、schema.id 查询VO实体
    //     const sessionId = '';
    //     this.metadataServ.GetRefMetadata('', schema.id, sessionId).subscribe(data => {

    //         if (data) {
    //             // 设计器自动补充的属性，不记录变更
    //             window.suspendChangesOnForm = true;

    //             const voMetadataPath = `${data.relativePath}/${data.fileName}`;

    //             schema.voPath = data.relativePath;
    //             schema.voNameSpace = data.nameSpace;

    //             // vo发布dll 获取eapiId
    //             this.http.post('/api/dev/main/v1.0/lookup/publish', '"' + voMetadataPath + '"', {
    //                 headers: new HttpHeaders({ 'Content-Type': 'text/json', SessionId: '' })
    //             }).subscribe((res: any) => {
    //                 if (res.success) {
    //                     // 设计器自动补充的属性，不记录变更
    //                     window.suspendChangesOnForm = true;

    //                     schema.eapiId = res.content.id;
    //                     schema.eapiCode = res.content.code;
    //                     schema.eapiName = res.content.name;
    //                     schema.eapiNameSpace = this.formBasicServ.formMetaBasicInfo.nameSpace;

    //                     window.suspendChangesOnForm = false;
    //                 }

    //                 // TODO 触发保存表单
    //             });

    //             window.suspendChangesOnForm = false;
    //         }

    //     }, error => {
    //         subject.next();
    //     });

    //     return subject;

    // }

    /**
     * 适配表单配置
     */
    private adaptFormOptions() {
        if (!this.domServ.options) {
            this.domServ.options = {};
        }
        if (!this.domServ.options.hasOwnProperty.call('renderMode')) {
            this.domServ.options.renderMode = 'compile';
        }

        if (!this.domServ.options.hasOwnProperty.call('changeSetPolicy')) {
            this.domServ.options.changeSetPolicy = 'valid';
        }

        if (!this.domServ.options.hasOwnProperty.call('enableServerSideChangeDetection')) {
            this.domServ.options.enableServerSideChangeDetection = false;
        }
    }
}
